grammar Bestpaper;  
options {  
    output=AST;  
    ASTLabelType=CommonTree;  
} 
tokens	{
	BOOK;
	CHAPTER;
	CHAPTER_HEADING;
	SECTION;
	PARAGRAPH;
	LEVEL1;
	LEVEL2;
	LEVEL3;
	LEVEL4;
	LEVEL5;
	LEVEL6;
	ROW;
}
@header {
package com.googlecode.bestpaper;
}
book
	:	(chapter NEWLINE+)* chapter NEWLINE* -> ^(BOOK chapter+);
chapter   
	:	chapter_heading NEWLINE+ (content NEWLINE+)? (section NEWLINE+)* section -> ^(CHAPTER chapter_heading content? section+)
	|	chapter_heading NEWLINE+ content -> ^(CHAPTER chapter_heading content)
	;     
chapter_heading
	:	SPACE? CH SPACE? title SPACE? CH SPACE? -> ^(CHAPTER_HEADING title);
section  
	:   heading NEWLINE+ content -> ^(SECTION heading content)
	|	heading -> ^(SECTION heading);    
heading  
    :	SPACE!? (heading1 | heading2 | heading3 | heading4 | heading5 | heading6) SPACE!? ;      
heading1  
    :   H1 SPACE? title SPACE? H1 -> ^(LEVEL1 title);  
heading2  
    :   H2 SPACE? title SPACE? H2 -> ^(LEVEL2 title);  
heading3  
    :   H3 SPACE? title SPACE? H3 -> ^(LEVEL3 title);  
heading4  
    :   H4 SPACE? title SPACE? H4 -> ^(LEVEL4 title);  
heading5  
    :   H5 SPACE? title SPACE? H5 -> ^(LEVEL5 title);  
heading6  
    :   H6 SPACE? title SPACE? H6 -> ^(LEVEL6 title);      
title     
    :   (WORD SPACE)* WORD;
content   
    :   (seg NEWLINE+)* seg -> ^(PARAGRAPH seg+);  
seg	
	:	row | line;
line  
    :	SPACE!? (WORD SPACE)* WORD SPACE!? | SPACE!;
row
	:	SPACE? (TABLE_BORD line)+ TABLE_BORD SPACE? -> ^(ROW line+);
	
TABLE_BORD
	:	'||';
CH
	:	'-';      
H1  
    :   '=';  
H2  
    :   '==';  
H3  
    :   '===';  
H4  
    :   '====';  
H5  
    :   '=====';  
H6  
    :   '======';         
NEWLINE   
    :   '\r'? '\n' ;  
SPACE     
    :   (' ' | '\t')+;  
WORD  
    :   (~('\r' | '\n' | ' ' | '\t'))+; 
